/*
 * @Description: 连接对应的Micro微服务（router中间件）
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-19 11:30:40
 * @LastEditTime: 2022-07-07 19:11:50
 */
import type Router from '@koa/router'
import Micro, { useConfig, log } from 'tcp-micro-service'

export default (): Router.Middleware => {
    // 读取配置
    const { registerServer } = useConfig()

    return async (ctx, next) => {
        // 请求路径
        const serviceName = ctx.request.path.match(/^\/api\/(?<service>[A-Za-z0-9_-]+)/)?.groups?.service
        const micro: Micro = ctx.micro

        // 查询当前服务器数据并连接
        // 先判断是否已连接
        if (!micro.hasSocket(serviceName)) {
            // 查询当前服务器数据
            const { ok, data, msg } = await micro.request({
                service: registerServer.name,
                path: `/find/${serviceName}`,
                data: { method: 'SYS' }
            })

            if (ok === 1) {
                // 连接此服务
                await new Promise((resolve, reject) => {
                    micro.client(data, (err) => {
                        if (err) {
                            reject(new Error(`服务 ${data.name} 连接失败：${err.message}`))
                            return
                        }
                        log.info(`已连接到 ${data.name} 服务`)
                        resolve(null)
                    })
                })
            } else {
                throw new Error(msg)
            }
        }

        await next()
    }
}